package persistencia;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

public class Abrir {
	static String path = "";
	static String lastPath = "";

	public Abrir() {
	}

	public void load() {
		JFileChooser file = new JFileChooser();
		file.setDialogTitle("Abrir arquivo");
		if (lastPath.equals("")) {
			File pathInicial = new File(path);
			file.setCurrentDirectory(pathInicial);
		} else {
			File pathInicial = new File(lastPath);
			file.setCurrentDirectory(pathInicial);
		}

		file.setFileFilter(new javax.swing.filechooser.FileFilter() {
			public boolean accept(File f) {
				return f.getName().toLowerCase().endsWith(".txt")
						|| f.isDirectory();
			}

			public String getDescription() {
				return "Arquivo texto (.txt)";
			}
		});

		int retorno = file.showOpenDialog(null);
		if (retorno == JFileChooser.APPROVE_OPTION) {
			path = file.getSelectedFile().getAbsolutePath();
			lastPath = path.substring(0, path.lastIndexOf("\\"));
			File newFile = new File(path);
			FileInputStream fis = null;

			try {
				fis = new FileInputStream(newFile);

				int content;
				while ((content = fis.read()) != -1) {
					System.out.print((char) content);
				}

			} catch (IOException e) {
				e.printStackTrace();
			}

			finally {
				try {
					if (fis != null)
						fis.close();
				}

				catch (IOException ex) {
					ex.printStackTrace();
				}
			}

		} else {
			JOptionPane.showMessageDialog(null, "Problema ao carregar o arquivo",
					"Error", 2);
		}
	}
}
